package c.c.d.s.s.o.c.as.context;

import c.c.d.s.s.o.c.as.util.response.SecurityResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 自定义的 ErrorController<br>
 * Ref: https://stackoverflow.com/questions/34366964/spring-boot-controlleradvice-exception-handler-not-firing
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-05-25 20:34
 */
@RestController
public class CustomErrorController extends BasicErrorController {

    private static final TypeReference<Map<String, Object>> mapTypeReference = new TypeReference<Map<String, Object>>() {
    };

    public CustomErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes, new ErrorProperties());
    }

    @RequestMapping
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        final Map<String, Object> body = getErrorAttributes(request, false);

        final HttpStatus status = getStatus(request);
        return
                new ResponseEntity<>(
                        JSON.parseObject(JSON.toJSONString(
                                new SecurityResponse.Builder().httpStatus(status).timestamp(LocalDateTime.now()).message((String) body.get("message")).build()),
                                mapTypeReference
                        ),
                        status
                );
    }

}